<?php
class BookController extends Controller
{
	
	
	public function getCacheId($type, $id) {
		return strtr(Yii::app()->params['bookCacheId'][$type], array('{id}'=>$id));
	}
	
	/**
	 * 获得章节评论
	 * @param int $bookId     书id
	 * @param int $chapterId  章节id
	 */
	public function getCommentsCounts($bookId, $chapterId) {
		$commentCounts = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_sections}}')
														->select('sectionId, commentsCounts')
														->where('chapterId=? and commentsCounts<>0', array($chapterId))
														->queryAll(false);
														
		return $commentCounts;
	}
	
	/**
	 * 获得章节信息
	 * @param string $flag
	 * @param string $chapter
	 */
	public function getChapterInfo($bookFlag, $chapterFlag) {
		$book = $this->getBookInfo($bookFlag);
		$cacheKey = $this->getCacheId('chapter', $bookFlag.$chapterFlag);
		$chapter = Yii::app()->cache->get($cacheKey);
		if ($chapter===false) {
			$chapter = Yii::app()->db->createCommand()
			->from('{{module_'. $book->moduleId .'_chapters}}')
			->where('url=?', array($chapterFlag))
			->queryRow();
			if ($chapter===false) $this->redirect(array('default/index','bookFlag'=>$bookFlag));
			Yii::app()->cache->set($cacheKey, $chapter, 86000);
		}
		return $chapter;
	}
	
	
	/**
	 * 获得书的信息
	 * @param string $flag 书名标识
	 */
	public function getBookInfo($bookFlag) {
		$cacheKey = $this->getCacheId('book', $bookFlag);
		$book = Yii::app()->cache->get($cacheKey);
		if ($book===false) {
			$book = Modules::model()->findByAttributes(array('nameFlag'=>$bookFlag));
			if (is_null($book)) $this->redirect('/');
			Yii::app()->cache->set($cacheKey, $book, 86000);
		}
		return $book;
	}
	
	/**
	 * 获得书的目录
	 * @param int $bookId  书的id
	 */
	public function getBookTableOfContents($bookId) {
		$cacheKey = $this->getCacheId('tableOfContents', $bookId);
		$tableOfContents = Yii::app()->cache->get($cacheKey);
		if ($tableOfContents===false) {
			$tableOfContents = Yii::app()->db->createCommand()
			->from('{{module_'. $bookId .'_chapters}}')
			->order('chapterSort DESC')->queryAll();
			Yii::app()->cache->set($cacheKey, $tableOfContents, 86000);
		}
		return $tableOfContents;
	}
	
	/**
	 * 获得段落列表
	 * @param int $bookId  书id
	 * @param int $chapterId 章id
	 */
	public function getSectionList($bookId, $chapterId) {
		$cacheKey = $this->getCacheId('section', $bookId.'_'.$chapterId);
		$sections = Yii::app()->cache->get($cacheKey);
		if ($sections==false) {
			$sections = Yii::app()->db->createCommand()->from('{{module_'. $bookId .'_sections}} s')
			->where('chapterId=?', array($chapterId))
			->order('s.sectionSort desc')
			->join('{{module_'. $bookId .'_translates}} t', 's.translateId=t.translateId')
			->queryAll();
	
			Yii::app()->cache->set($cacheKey, $sections, 86000);
		}
		return $sections;
	}
	
	/**
	 * 创建导航
	 * @param string $bookFlag 书标识
	 * @param array $chapter  章节信息
	 */
	public function createNav($bookFlag, $chapter, $lang="zh") {
		if ($lang == 'en') {
			$tableofcontent = "table of content";
			$nextTitle = "next";
			$previousTitle = "previous";
		}
		else {
			$tableofcontent = "目录";
			$nextTitle = "下一章";
			$previousTitle = "上一章";
		}

		$prefixUrl = $this->createUrl('default/chapter', array('bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl']));
		if ($chapter['isFirst']==1) {
			$this->nav = CHtml::link($tableofcontent, $this->createUrl('default/index', array('bookFlag'=>$bookFlag, 'lang'=>$lang)));
			$this->nav .= ' &loz; '. CHtml::link($nextTitle.' &raquo;', $this->createUrl('default/chapter', array('lang'=>$lang, 'bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl'])));
		}
		else if ($chapter['isEnd']==1) {
			$this->nav = CHtml::link('&laquo; '. $previousTitle, $this->createUrl('default/chapter', array('lang'=>$lang, 'bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['prevUrl']))) .' &loz; ';
			$this->nav .= CHtml::link($tableofcontent, $this->createUrl('default/index', array('bookFlag'=>$bookFlag, 'lang'=>$lang)));
		}
		else if ($chapter['isEnd']==0 && $chapter['isFirst']==0) {
			$this->nav = CHtml::link('&laquo; '. $previousTitle, $this->createUrl('default/chapter', array('lang'=>$lang, 'bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['prevUrl']))) .' &loz; ';
			$this->nav .= CHtml::link($tableofcontent, $this->createUrl('default/index', array('bookFlag'=>$bookFlag, 'lang'=>$lang)));
			$this->nav .= ' &loz; '. CHtml::link($nextTitle. ' &raquo;', $this->createUrl('default/chapter', array('lang'=>$lang, 'bookFlag'=>$bookFlag, 'chapterFlag'=>$chapter['nextUrl'])));
		}
	}
	

	/**
	 * 创建快速导航
	 * @param int $bookId
	 * @param int $chapterId
	 */
	public function createExpressNavContent($bookId, $chapterId, $lang="zh") {

		$cacheKey = $this->getCacheId('expressNav', $bookId.'-'.$chapterId."-".$lang);

		$expressNavContent = Yii::app()->cache->get($cacheKey);
		if ($expressNavContent==false) {
			$expressNavContent  = $this->getChapterNavByParentTitleId($bookId, $chapterId, $lang);
			Yii::app()->cache->set($cacheKey, $expressNavContent, 86000);
		}
		
		return $expressNavContent;
	}
	
	/**
	 * 获得父级标题
	 * @param unknown_type $chapter_id
	 * @param unknown_type $title_parent
	 * @return string
	 */
	public function getChapterNavByParentTitleId($bookId, $chapterId, $lang, $titleParent=0) {
		static $_i = 0;
		$text = "";
		if ($_i==0) {
			$sql = "
			SELECT * FROM {{module_{$bookId}_sections}} s, {{module_{$bookId}_translates}} t
			WHERE s.chapterId={$chapterId} AND s.sectionType=". SectionHelper::SECTION_TYPE_TITLE ."
			AND s.titleParent={$titleParent} AND
			s.translateId = t.translateId
			ORDER BY s.sectionSort DESC
			";
		}
		else {
			$sql = "
			SELECT * FROM {{module_{$bookId}_sections}} s, {{module_{$bookId}_translates}} t
			WHERE s.chapterId={$chapterId} AND s.titleParent={$titleParent} AND
			s.translateId = t.translateId
			ORDER BY s.sectionSort DESC
			";
		}
		$datas = Yii::app()->db->createCommand($sql)->queryAll();
		$fieldName = $lang == 'en' ? 'originalSection' : 'sectionText';
		if (count($datas)>0) $text="<ul style=\"list-style-type:auto;\">";
		foreach($datas as $data) {
			$text.="<li><a href=\"#cn".$data['sectionId']."\" onClick=\"toggleChapternav()\" style=\"color:#599ACB;\">". $data[$fieldName] ."</a>".$this->getChapterNavByParentTitleId($bookId, $chapterId, $lang, $data['sectionId'])."</li>";
		}
	
		if (count($datas)>0) $text.="</ul>";
		$_i++;
		return $text;
	}
	
	/**
	 * 获得评论列表
	 * @param string $bookFlag
	 * @param string $chapterFlag
	 */
	public function getComments($bookFlag, $chapterFlag) {
		$cacheKey = $this->getCacheId('comments', $bookFlag);
		$commentsString = Yii::app()->cache->get($cacheKey);
		
		if ($commentsString===false) {
			$book = $this->getBookInfo($bookFlag);
			$bookId = $book->moduleId;
			$chapter = $this->getChapterInfo($bookFlag, $chapterFlag);
			$chapterId = $chapter['chapterId'];
			
			$comments = Yii::app()->db->createCommand()->from('{{module_'.$bookId.'_comments}}')
													->order('addTime desc')
													->queryAll();
		
			$commentsString = '';
			foreach( $comments as $comment) {
				if (trim($comment['website'])=='') {
					$link = CHtml::encode($comment['name']);
				}
				else {
					$link = CHtml::link(CHtml::encode($comment['name']), $comment['website']);
				}
				$date = CHtml::tag('span', array('class'=>'meta'), date("Y-m-d H:i:s", $comment['addTime']));
				$content = "<dd>". CHtml::tag('p', array(), CHtml::encode($comment['comment'])) ."</dd>";
				$li_content = "<dl><dt>".$link.' '.$date."</dt>". $content."</dl>";
				$commentsString .= CHtml::tag('li',array('class'=>'comment', 'id'=> $comment['commentId']), $li_content)."\n";
			}
		
			Yii::app()->cache->set($cacheKey, $commentsString, 86000);
		}
		echo $commentsString;
	}
	
	public function saveComments($bookFlag, $chapterFlag) {
		$_errors = array();
		$comment = Yii::app()->request->getPost('comment');
		
		if ('' == trim($comment)) $_errors[]='comment';
		
		$email = Yii::app()->request->getPost('email');
		if ('' == trim($email)) $_errors[]='email';
		
		$name = Yii::app()->request->getPost('name');
		if ('' == trim($name)) $_errors[]='name';
		
		$nodenum = Yii::app()->request->getPost('nodenum');
		$url = Yii::app()->request->getPost('url');
		
		if (count($_errors)>0) {
			echo CJSON::encode($_errors);
			exit;
		}
		
		$book = $this->getBookInfo($bookFlag);
		$bookId = $book->moduleId;
		$chapter = $this->getChapterInfo($bookFlag, $chapterFlag);
		$chapterId = $chapter['chapterId'];
		
		$params = array(
					'comment'=>$comment,
					'email'=>$email,
					'name'=>$name,
					'website'=>$url,
					'sectionId'=>$nodenum,
					'clientIp'=>AppHelper::getClientIp(),
					'addTime'=>time(),
					'chapterId'=>$chapterId
				);
		$sql = "
			INSERT INTO {{module_".$bookId."_comments}} (
				name, email, website, comment, clientIp, addTime, sectionId, chapterId
			) VALUES (:name, :email, :website, :comment, :clientIp, :addTime, :sectionId, :chapterId)
		";
		if (Yii::app()->db->createCommand($sql)->execute($params)!=false) {
			$commentId = Yii::app()->db->getLastInsertID();
			$link = CHtml::link($name, $url);
			$date = CHtml::tag('span', array('class'=>'meta'), date("Y-m-d H:i:s", $params['addTime']));
			$content = "<dd>". CHtml::tag('p', array(), $comment) ."</dd>";
			$li_content = "<dl><dt>".$link.$date."</dt>".$content."</dl>";
			echo CHtml::tag('li',array('class'=>'comment', 'id'=> $commentId, $li_content));
			
			//更新段落评论数
			Yii::app()->db->createCommand()->update('{{module_'.$bookId.'_sections}}', 
													array('commentsCounts'=>new CDbExpression('commentsCounts+1')),
													'sectionId='.$nodenum
												);
			
			//清除本章评论数据缓存
			Yii::app()->cache->delete($this->getCacheId('commentsCounts', $bookFlag.'_'.$chapterFlag));
			//清除显示评论
			Yii::app()->cache->delete($this->getCacheId('sectionComments', $bookFlag.'-'.$chapterFlag.'-'.$nodenum));
			//清除所有评论
			Yii::app()->cache->delete($this->getCacheId('comments', $bookFlag));
		}
	}
}
